<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Category extends CI_Controller {
	

	public function index() {
		
	}

	public function getCats($type) {
		$this->load->model('Model_lesson');
		$cursor = $this->Model_lesson->getCats($type);
		sleep(1);
		$cursor->sort(array('_id'=>1));

		// Conver mongoCursor to JSON
		$arr = [];
		foreach(iterator_to_array($cursor) as $cat) {
			array_push($arr, $cat);
		}
		$fullArr = [];
		foreach($arr as $cat) {
			$num = $this->Model_lesson->countCatLessons($cat['_id']);
			$cat['numLesson'] = $num;
			array_push($fullArr, $cat);
		}
		echo json_encode($fullArr);	
	}

	public function getAllCats() {
		$this->load->model('Model_category');
		$cursor = $this->Model_category->getCats();

		echo json_encode(iterator_to_array($cursor));
	}

	public function getSection() {
		$this->load->model('Model_category');
		$cursor = $this->Model_category->getSections();
		$arr = array();
		foreach (iterator_to_array($cursor) as $cat) {
			array_push($arr, $cat);
		}
		echo json_encode($arr);
	}

	public function getLsByCat($id) {
		$this->load->model('Model_lesson');

		$idArr = array();
		array_push($idArr, $id);

		$cursor = $this->Model_lesson->getChildCats($id);
		foreach(iterator_to_array($cursor) as $val) {
			$id = $val['_id'];
			array_push($idArr, $id);
		}

		$cursor = $this->Model_lesson->getLsByCats($idArr);
		$cursor->sort(array('name'=>1));
		
		// Conver mongoCursor to JSON
		echo json_encode(iterator_to_array($cursor));
	}
	public function getHeaderCat($id) {
		$this->load->model('Model_category');
		$cursor = $this->Model_category->getCat($id);

		echo json_encode($cursor);
	}

}

?>